package com.xiao.dynamic_rule.utils;

import com.xiao.dynamic_rule.pojo.RuleParamAtomic;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 通过条件参数生成查询clickhouse的sql
 */
public class ClickhouseCountQueryUtil {

    public static String getSql(String deviceId,RuleParamAtomic atomicParam){

        String template1 =
                "select \n" +
                "deviceId,\n" +
                "count()\n" +
                "from default.yinew_detail\n" +
                "where deviceId = '" + deviceId +"'\n" +
                "and eventId = '" + atomicParam.getEventId() + "'\n" +
                "and timeStamp >= '"+ atomicParam.getRangeStart() +"'\n" +
                "and timeStamp <= '" + atomicParam.getRangeEnd()+"'\n"
                ;
        String template3 = "group by deviceId";
        HashMap<String, String> properties = atomicParam.getProperties();
        Set<Map.Entry<String, String>> entries = properties.entrySet();
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : entries) {
            // "and properties['pageId'] = 'page006'"
            sb.append("and properties['"+ entry.getKey() +"'] = '" + entry.getValue() + "'\n");
        }

        return template1+sb.toString()+template3;
    }

    public static void main(String[] args) {
        RuleParamAtomic ruleAtomicParam = new RuleParamAtomic();
        ruleAtomicParam.setEventId("R");
        HashMap<String, String> props = new HashMap<>();
        props.put("p1","v2");
        props.put("p3","v4");
        props.put("p7","v5");
        ruleAtomicParam.setProperties(props);
        ruleAtomicParam.setRangeStart(1616925000815L);
        ruleAtomicParam.setRangeEnd(1616925004815L);

        String sql = getSql("000001", ruleAtomicParam);
        System.out.println(sql);
    }

}
